﻿using Newtonsoft.Json.Linq;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;
using SU.Center.Infa.Migrations;
using System.Security.Cryptography;

namespace SU.Center.Api
{
    public class QiniuUtils
    {

        private readonly IConfiguration _configuration;

        public QiniuUtils(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 上传文件到七牛云,并返回上传后的地址
        /// </summary>
        /// <param name="data">图片字节</param>
        /// <param name="saveKey">新文件名称</param>
        /// <returns></returns>
        public string UploadFile(byte[] data, string saveKey)
        {

            // 从配置中获取 AccessKey 和 SecretKey
            var accessKey = _configuration["QiNiu:AccessKey"];
            var secretKey = _configuration["QiNiu:SecretKey"];

            string bucket = "shenlitao";

            // 创建上传策略
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = bucket + ":" + saveKey;
            // 设置上传凭证有效期（示例2小时，可调整）
            putPolicy.SetExpires(3600);

            // 自动选择区域
            Qiniu.Common.Config.AutoZone(accessKey, bucket, false);

            // 生成上传凭证
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(new Mac(accessKey, secretKey), jstr);
            FormUploader fu = new FormUploader();

            HttpResult result = fu.UploadData(data, saveKey, token);
            if (result.Code == 200)
            {
                JObject jsonObject = JObject.Parse(result.Text);
                string key = jsonObject["key"].ToString();
                return "http://soq9dcnue.hb-bkt.clouddn.com/" + key;
            }
            else
            {
                Console.WriteLine("上传失败: " + result.Text);
                return "";
            }
        }
    }
}
